package org.jeecg.modules.shiro;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.authc.pam.UnsupportedTokenException;
import org.apache.shiro.realm.Realm;

import java.util.Collection;

/**
 * TODO: 自定义身份验证器，根据登录使用Token匹配调用对应的Realm
 *
 * @author Zhang Hao yu
 * @date 2020/11/12 21:34
 */
public class CustomModularRealmAuthenticator extends ModularRealmAuthenticator {
    /**
     * TODO: 自定义realm的分配策略  通过realm.supports()来判断
     *
     *
     * @author ZhangHaoyu
     * @param realms
     * @param token
     * @return org.apache.shiro.authc.AuthenticationInfo
     */
    @Override
    protected AuthenticationInfo doMultiRealmAuthentication(Collection<Realm> realms, AuthenticationToken token) {
        // 断言getRealms是否返回为空
        assertRealmsConfigured();

        Realm uniqueRealm = null;
        for (Realm realm: realms) {
            if (realm.supports(token)){
                uniqueRealm = realm;
                break;
            }
        }

        if (uniqueRealm==null){
            throw new UnsupportedTokenException();
        }

        return uniqueRealm.getAuthenticationInfo(token);
    }
}